const { SysRole, SysMenu, SysRoleMenu, sequelize } = require('../config/Sequelize')
const { CriteriaExample } = require('../utils/CriteriaExample')

/**
 * 查询角色列表
 * @param {*} role 
 * @returns 
 */
const selectRoleList = async (param = {}) => {
  // 创建查询条件对象
  const example = new CriteriaExample(param)
  example.and()
    .eq('roleId')
    .like('roleName')
    .eq('dataScope')
    .eq('status')
    .between('createdAt')
  const page = example.getPage()
  const data = await SysRole.findAll({
    where: example.getWhere(),
    order: [['createdAt', 'ASC']],
    include: SysMenu,
    ...page
  })
  // 查询总记录数
  const total = await SysRole.count();
  return { ...page, total, data }
}


/**
 * 根据用户id查询用户信息
 * @param {*} id 
 * @returns 
 */
const selectRoleById = async (id) => {
  const role = await SysRole.findOne({
    where: {
      roleId: id
    }
  })
  return role
}

/**
 * 添加角色信息
 * @param {*} role 
 * @returns 
 */
const addRole = (role) => {
  return SysRole.create(role)
}

/**
 * 更新角色信息
 * @param {*} role 
 * @returns 
 */
const updateRole = (role) => {
  return SysRole.update(role, {
    where: {
      roleId: role.roleId
    }
  })
}


/**
 * 删除角色信息
 * @param {*} id 
 * @returns 
 */
const deleteRole = (id) => {
  return SysRole.destroy({
    where: { roleId: id }
  })
}


/**
 * 根据角色id查询角色与菜单关系信息
 * @param {*} roleId 
 * @returns 
 */
const selectRoleIdAndMenuIdsByRoleId = async (roleId) => {
  return await SysRoleMenu.findAll({
    where: {
      roleId
    }
  })
}

/**
 * 批量添加 菜单与角色关系数据
 * @param {*} roleIdAndMenuIds 
 * @returns 
 */
const bulkAddMenuIdAndRoleId = async (roleIdAndMenuIds) => {
  // 使用 bulkCreate 进行批量插入
  return await SysRoleMenu.bulkCreate(roleIdAndMenuIds)
}

/**
 * 删除 菜单与角色关系数据
 * @param {*} roleId 
 * @returns 
 */
const delRoleIdAndMenuIdByRoleId = async (roleId) => {
  return await SysRoleMenu.destroy({
    where: { roleId: roleId }
  })
}




module.exports = {
  selectRoleList,
  selectRoleById,
  addRole,
  updateRole,
  deleteRole,
  bulkAddMenuIdAndRoleId,
  delRoleIdAndMenuIdByRoleId,
  selectRoleIdAndMenuIdsByRoleId
}